//
//  JFBStaffDS.m
//  ios-supplier 定义配送员的相关操作
//
//  Created by feynmanyuan on 15/4/17.
//  Copyright (c) 2015年 feynmanyuan. All rights reserved.
//
//

#import "JFBStaffDS.h"
#import "JFBStaff.h"
#import "JFBBaseStorage.h"

@implementation JFBStaffDS

- (instancetype)initWithAttributes:(NSDictionary *)attributes {
    self = [super init];
    if (!self) {
        return nil;
    }
    
    self.Id = [[attributes objectForKey: @"id"] isEqual: [NSNull null]] ? 0 : [[attributes objectForKey: @"id"]  integerValue];
    self.name = [[attributes objectForKey: @"name"] isEqual: [NSNull null]] ? 0 : [attributes objectForKey: @"name"];
    self.telephone = [[attributes objectForKey: @"telephone"] isEqual: [NSNull null]] ? 0 : [attributes objectForKey: @"telephone"];
    self.isDefault = [[attributes objectForKey: @"isDefault"] isEqual: [NSNull null]] ? 0 : [[attributes objectForKey: @"isDefault"] integerValue];
    self.isAvailable = [[attributes objectForKey:@"isAvailable"] isEqual:[NSNull null]] ? 0 : [attributes objectForKey:@"isAvailable"];
    self.merchantDeliverId = [[attributes objectForKey:@"merchantDeliverId"] isEqual:[NSNull null]] ? 0 : [[attributes objectForKey:@"merchantDeliverId"] integerValue];
    return self;
}

// 加载配送员列表
+ (NSURLSessionDataTask *)loadStaffList:(void (^)(NSArray *staffList, NSError *error))block pager:(JFBPager*)pager{
    NSDictionary *dic = @{@"ut":[[NSUserDefaults standardUserDefaults]objectForKey:@"ut"]};
    return [[JFBAPIClient sharedClient:true] GET:@"/back-user/queryDeliverListByMerchantId.do" parameters:dic success:^(NSURLSessionDataTask * __unused task, id JSON) {
        NSObject * error = [JSON valueForKey:@"code"];
        NSLog(@"%@", JSON);
        if( [error isEqual:@"0"] ) {
            NSMutableArray *result = [@[] mutableCopy];
            NSArray *loginResponse = [JSON valueForKeyPath:@"data"];
            for( NSDictionary *staff in loginResponse ) {
                JFBStaffDS * ds = [[JFBStaffDS alloc] initWithAttributes:staff];
                [result addObject:ds];
            }
            
            block([NSArray arrayWithArray:result], nil);
        }else if ([JSON[@"code"] integerValue] == 99){
            UIViewController* viewController;
            UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            viewController = [mainStoryBoard instantiateViewControllerWithIdentifier:@"Login"];
        }else {
            block(nil, nil);
        }
    } failure:^(NSURLSessionDataTask *__unused task, NSError *error) {
        block(nil, error);
    }];
}

// 删除配送员
+ (NSURLSessionDataTask *)deleteStaff:(void (^)(BOOL isSuccess, NSError *error))block staffID:(NSUInteger)staffID {
    NSDictionary *staffParams = @{@"deliverId": [NSNumber numberWithInteger:staffID],@"ut":[[NSUserDefaults standardUserDefaults]objectForKey:@"ut"]};
    return [[JFBAPIClient sharedClient:true] GET:@"/back-user/deleteDeliverByMerchant.do" parameters:staffParams success:^(NSURLSessionDataTask * __unused task, id JSON) {
        NSObject * error = [JSON valueForKey:@"code"];
        if( [error isEqual:@"0"] ) {
            [self deleteDefaultStaff];
            block(true, nil);
        } else if ([JSON[@"code"] integerValue] == 99){
            UIViewController* viewController;
            UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            viewController = [mainStoryBoard instantiateViewControllerWithIdentifier:@"Login"];
        }else {
            block(false, nil);
        }
    } failure:^(NSURLSessionDataTask *__unused task, NSError *error) {
        block(false, error);
    }];
    return nil;
}

// 新增配送员
+ (NSURLSessionDataTask *)addStaff:(void (^)(BOOL isSuccess, NSString *message, NSError *error))block staff:(JFBStaffDS*)staff {
    NSDictionary *staffParams = @{@"name": staff.name, @"telephone":staff.telephone, @"isDefault": staff.isDefault == 0 ? @(NO) : @(YES),@"isAvailable":staff.isAvailable == 0?@(NO):@(YES),@"ut":[[NSUserDefaults standardUserDefaults]objectForKey:@"ut"]};
    return [[JFBAPIClient sharedClient:true] GET:@"/back-user/addDeliverByMerchant.do" parameters:staffParams success:^(NSURLSessionDataTask * __unused task, id JSON) {
        NSObject * error = [JSON valueForKey:@"code"];
        if( [error isEqual:@"0"] ) {
            block(true, @"添加成功", nil);
        } else if ([JSON[@"code"] integerValue] == 99){
            UIViewController* viewController;
            UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            viewController = [mainStoryBoard instantiateViewControllerWithIdentifier:@"Login"];
        }else {
            block(false, @"请填写配送员信息", nil);
        }
    } failure:^(NSURLSessionDataTask *__unused task, NSError *error) {
        block(false, @"添加失败", error);
    }];
    return nil;
}

// 更新配送员信息
+ (NSURLSessionDataTask *)updateStaff:(void (^)(BOOL isSuccess, NSString *message, NSError *error))block staff:(JFBStaffDS*)staff {
    NSDictionary *staffParams = @{ @"deliverId":[NSNumber numberWithInteger:staff.Id],
                                   @"name": staff.name,
                                   @"telephone":staff.telephone,
                                   @"isDefault": staff.isDefault == 0 ? @(NO) : @(YES),
                                   @"isAvailable":staff.isAvailable,
                                   @"merchantDeliverId":@(staff.merchantDeliverId)
                                   };
    
    return [[JFBAPIClient sharedClient:true] GET:@"/back-user/updateDeliverByMerchant.do" parameters:staffParams success:^(NSURLSessionDataTask * __unused task, id JSON) {
        NSObject * error = [JSON valueForKey:@"code"];
        if( [error isEqual:@"0"] ) {
            block(true, @"更新成功", nil);
        } else {
            NSObject * errorMsg = [JSON valueForKey:@"error"];
            block(false, [NSString stringWithFormat:@"%@", errorMsg], nil);
        }
    } failure:^(NSURLSessionDataTask *__unused task, NSError *error) {
        block(false, @"更新失败", error);
    }];
    
    return nil;
}

//+(JFBStaffDS*)loadFromDB {
//    JFBBaseStorage *_store = [JFBBaseStorage getStore];
//    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"JFBStaff"];
//    NSError *error;
//    NSArray *array = [_store.managedObjectContext executeFetchRequest:request error:&error];
//    JFBStaff *staffInfo;
//    
//    if( array.count <= 0 ) {
//        return nil;
//    } else {
//        staffInfo = [array objectAtIndex:0];
//    }
//    
//    JFBStaffDS *ds = [[JFBStaffDS alloc] init];
//    
//    ds.ID = [staffInfo.staff_id intValue];
//    ds.name = staffInfo.name;
//    ds.mobile = staffInfo.mobile;
//    ds.isDefault = 1;
//    
//    return ds;
//}

//+(void)getDefaultStaff:(void (^)(JFBStaffDS *staff, NSError *error))block{
//    JFBStaffDS * ds = [JFBStaffDS loadFromDB];
//    if( ds == nil ) {
//        [JFBStaffDS loadStaffList:^(NSArray *staffList, NSError *error) {
//            block([JFBStaffDS loadFromDB], nil);
//        } pager:nil];
//    } else {
//        block(ds, nil);
//    }
//}

+(void)deleteDefaultStaff{
    JFBBaseStorage *_store = [JFBBaseStorage getStore];
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"JFBStaff"];
    NSError *error;
    NSArray *array = [_store.managedObjectContext executeFetchRequest:request error:&error];
    JFBStaff *staff;
    if( array.count != 0 ) {
        staff = [array objectAtIndex:0];
        [_store.managedObjectContext deleteObject:staff];
        [_store.managedObjectContext save:&error];
    }
}

//+(JFBStaffDS*)saveStaffInfo:(JFBStaffDS*)staffDS{
//    JFBBaseStorage *_store = [JFBBaseStorage getStore];
//    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"JFBStaff"];
//    NSError *error;
//    NSArray *array = [_store.managedObjectContext executeFetchRequest:request error:&error];
//    JFBStaff *staffInfo;
//    
//    if( array.count > 0 ) {
//        staffInfo = [array objectAtIndex:0];
//        if ( [staffInfo.staff_id intValue] != staffDS.Id ) {
//            [_store.managedObjectContext deleteObject:staffInfo];
//            [_store.managedObjectContext save:&error];
//            array = nil;
//        }
//    }
//    
//    if( array == nil || array.count <= 0 ) {
//        staffInfo = (JFBStaff*)[NSEntityDescription insertNewObjectForEntityForName:@"JFBStaff" inManagedObjectContext:[_store managedObjectContext]];
//    } else {
//        staffInfo = [array objectAtIndex:0];
//    }
//    
//    staffInfo.staff_id = [NSNumber numberWithInteger:staffDS.Id];
//    staffInfo.name = staffDS.name;
//    staffInfo.telephone = staffDS.telephone;
//    
//    [_store.managedObjectContext save:&error];
//    
//    return [self loadFromDB];
//}


@end
